<template>
  <div>
    <el-drawer
      :visible.sync="dialogVisible"
      :before-close="handleDialogClose"
      :close-on-press-escape="false"
      :class="{'mobile-file-drawer': showMobilePage}"
      :size="showMobilePage ? '100%' : 1000">
      <DialogTitle slot="title" :title="drawerTitle"/>
      <div v-if="fileDesc" class="file-desc">{{ fileDesc }}</div>
      <div class="dialog-content">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          :show-advanced-filter="false"
          :class="showMobilePage && 'mobile-filter-box'"
          style="margin-bottom: 12px"
          show-search-btn
          line-feed
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"/>
        <div v-if="showSearchTips" class="search-tip">为你找到相关结果<span> {{ fileList.length }} </span>条</div>
        <div v-if="curFilePath.length" class="file-path">
          <span class="active-path" @click="folderChange(0)">全部</span>
          <template v-for="(path, index) in curFilePath">
            <span :key="path.id" @click="folderChange(index + 1)">
              <span style="color: #999"> / </span>
              <span :class="index === curFilePath.length - 1 ? 'default-path' : 'active-path'">{{ path.fileName }}</span>
            </span>
          </template>
        </div>
        <el-table
          v-loading="listLoading"
          v-if="fileList && fileList.length"
          ref="fileListRef"
          :data="fileList"
          :row-height="rowHeight()"
          :row-class-name="tableRowClassName"
          :header-cell-style="headerCellStyle"
          class="fb-table file-table"
          header-cell-class-name="order-data-header-cell"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          fit
          hightlight-current-row
          @select="selectTable"
          @select-all="selectTable"
          @sort-change="sortMethod">
          <el-table-column :fixed="selectFixed" align="center" type="selection" width="50"/>
          <el-table-column align="left" label="文件名称" min-width="150">
            <template slot-scope="scope">
              <el-tooltip v-if="scope.row.fileName" :open-delay="800" placement="top-start" effect="dark">
                <div slot="content" style="max-width: 200px;">{{ scope.row.fileName }}</div>
                <div class="ellipsisOne">
                  <img :src="scope.row.isFolder ? folderIcon : fileIcon" class="file-icon">
                  <span :class="{'linkName':isDocx(scope.row.fileName) || scope.row.isFolder}" @click="onViewFile(scope.row)">{{ scope.row.fileName }}</span>
                </div>
              </el-tooltip>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column sortable="custom" prop="createTime" align="left" label="创建时间" min-width="140">
            <template slot-scope="scope">
              <div class="resource-name">
                <span v-if="scope.row.createTime">
                  {{ scope.row.createTime | format('YYYY/MM/DD HH:mm') }}
                </span>
                <span v-else>--</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="creator" label="创建人" min-width="100">
            <template slot-scope="scope">
              <div>{{ scope.row.creator || '--' }}</div>
            </template>
          </el-table-column>
          <el-table-column :width="showMobilePage ? 50 : 150" align="left" label="操作" fixed="right">
            <template slot-scope="scope">
              <div v-if="!showMobilePage" class="action-btn-group" >
                <el-button :disabled="!isDocx(scope.row.fileName) && !scope.row.isFolder" :style="{color:isDocx(scope.row.fileName) || scope.row.isFolder? '#406EFF' : '#bbb'}" type="text" class="split-line" @click="onViewFile(scope.row)">查看</el-button>
                <template v-if="scope.row.isFolder">
                  <el-button v-if="showEditBtn(scope.row.creatorId)" type="text" style="color: #406EFF" class="split-line" @click="showFolderDialog(true, scope.row)">编辑</el-button>
                  <el-button v-else type="text" disabled class="split-line" style="margin-left: 10px">编辑</el-button>
                </template>
                <el-dropdown v-else trigger="click">
                  <el-button type="text" class="download-btn split-line">下载</el-button>
                  <el-dropdown-menu slot="dropdown" style="margin-top: 3px; margin-right: -30px; padding: 0;">
                    <el-dropdown-item :style="{ cursor: downloadLoading ? 'not-allowed' : 'pointer'}" :disabled="!isFill" style="width: 90px; text-align: center; padding: 0">
                      <el-button :loading="downloadLoading" :disabled="!isFill" type="text" @click="onDownloadFile(scope.row, 1)">填充模板</el-button>
                    </el-dropdown-item>
                    <el-dropdown-item v-if="isDocx(scope.row.fileName)" :style="{ cursor: downloadLoading ? 'not-allowed' : 'pointer'}" style="width: 90px; text-align: center; padding: 0">
                      <el-button :loading="downloadLoading" type="text" @click="onDownloadFile(scope.row, 2)">空模板</el-button>
                    </el-dropdown-item>
                    <el-dropdown-item :style="{ cursor: downloadLoading ? 'not-allowed' : 'pointer'}" style="width: 90px; text-align: center; padding: 0">
                      <el-button :loading="downloadLoading" type="text" @click="onDownloadFile(scope.row, 3)">原文件</el-button>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
                <el-button v-if="showDelBtn(scope.row.creatorId)" type="text" style="color: #FF4E5F; margin-left: 10px" @click="onDelete(scope.row)">删除</el-button>
                <el-button v-else type="text" disabled style="margin-left: 10px">删除</el-button>
              </div>
              <tableOperateBtn v-else>
                <el-dropdown-item :disabled="!isDocx(scope.row.fileName) && !scope.row.isFolder" style="width:90px;text-align: center" @click.native="onViewFile(scope.row)">
                  <div style="font-size: 14px">查看</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.isFolder" :disabled="!showEditBtn(scope.row.creatorId)" style="width:90px;text-align: center" @click.native="showFolderDialog(scope.row)">
                  <div style="font-size: 14px">编辑</div>
                </el-dropdown-item>
                <el-dropdown-item v-else style="width:90px;text-align: center" @click.native="handlerCreateNew(scope.row)">
                  <el-dropdown trigger="click">
                    <el-button type="text" class="download-btn split-line">下载</el-button>
                    <el-dropdown-menu slot="dropdown" style="margin-top: 3px; margin-right: -30px; padding: 0;">
                      <el-dropdown-item :style="{ cursor: downloadLoading ? 'not-allowed' : 'pointer'}" :disabled="!isFill" style="width: 90px; text-align: center; padding: 0">
                        <el-button :loading="downloadLoading" :disabled="!isFill" type="text" @click="onDownloadFile(scope.row, 1)">填充模板</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item v-if="isDocx(scope.row.fileName)" :style="{ cursor: downloadLoading ? 'not-allowed' : 'pointer'}" style="width: 90px; text-align: center; padding: 0">
                        <el-button :loading="downloadLoading" type="text" @click="onDownloadFile(scope.row, 2)">空模板</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item :style="{ cursor: downloadLoading ? 'not-allowed' : 'pointer'}" style="width: 90px; text-align: center; padding: 0">
                        <el-button :loading="downloadLoading" type="text" @click="onDownloadFile(scope.row, 3)">原文件</el-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-dropdown-item>
                <el-dropdown-item :disabled="!showDelBtn(scope.row.creatorId)" style="width:90px;text-align: center" @click.native="onDelete(scope.row)">
                  <div style="font-size: 14px">删除</div>
                </el-dropdown-item>
              </tableOperateBtn>
            </template>
          </el-table-column>
        </el-table>
        <div v-else class="empty-container">
          <img :src="EmptyImg">
          <div class="empty-text">{{ showSearchTips ? '暂无相关结果，请换个关键词试试' : '暂无文件' }}</div>
        </div>
      </div>
      <div class="dialog-footer">
        <OrderUpload :extend-params="setExtendParams" :accept="fileAccept" import-api="admin/contract/template/import" class="template-upload-box" style="padding: 0 32px;" @getList="queryFileList">
          <el-button slot="upload-body" class="btn" type="primary" size="small">上传文件</el-button>
        </OrderUpload>
        <el-button class="btn empty-btn-style" type="primary" size="small" @click="showFolderDialog(false)">添加文件夹</el-button>
        <el-button v-if="showBatchDelBtn" :disabled="!multipleSelectionAll.length" class="btn" size="small" type="danger" plain style="margin-right: 0" @click="onDelete">批量删除</el-button>
      </div>
    </el-drawer>
    <StoreFolder
      ref="storeFolderDialog"
      v-model="folderData"
      :is-edit="isEdit"
      @handleFolderEdit="handleFolderEdit"
      @handleFolderCreate="handleFolderCreate"
      @handleCancel="resetFolderData"
    />
    <ContractPreview
      ref="ContractPreviewRef"
      :file-data="previewFileData"
      :file-list="fileList"
      :preview-path="previewPath"
      :is-fill="isFill"
      :download-loading="downloadLoading"
      @onDownloadFile="onDownloadFile"
      @setDownloadParams="setDownloadParams"/>
  </div>
</template>

<script>
import DialogTitle from '@/components/Title';
import OrderUpload from '@/components/OrderList/orderUpload';
import ContractPreview from './contractPreview';
import StoreFolder from './modal/storeFolder';
import tableSelections from '@/mixins/tableSelections';
import mobileTable from '@/mixins/mobileTable';
import EmptyImg from '@/assets/empty-table-data.png';
import fileIcon from '@/assets/legal/file_icon.png';
import folderIcon from '@/assets/legal/folder_icon.png';
import { format } from '@/filters/date';
import { downloadFile } from '@/utils';
import { showModal } from '@/utils/message';
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
import {
  queryTemplateList,
  storeContractTemplate,
  editContractTemplate,
  deleteContractTemplate
} from '@/api/legal';

export default {
  name: 'ContractTemplate',
  filters: { format },
  components: {
    DialogTitle,
    StoreFolder,
    ContractPreview,
    OrderUpload
  },
  mixins: [tableSelections, mobileTable],
  props: {
    isFill: {
      type: Boolean,
      default: true
    },
    contractType: { // 合同类型
      type: [Number, String],
      default: null
    },
    previewPath: { // 预览文件地址
      type: String,
      default: ''
    },
    downloadLoading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      EmptyImg,
      fileIcon,
      folderIcon,
      dialogVisible: false,
      paramsObj: {},
      ids: '',
      tableRefName: 'fileListRef',
      idKey: 'id',
      isEdit: false,
      showSearchTips: false,
      listLoading: false,
      folderData: {
        fileName: '',
        fileDesc: '',
        parentId: null,
        id: null
      },
      sortName: '',
      sortType: '',
      fileList: [],
      curFolderId: '', // 当前文件夹id
      fileDesc: '', // 文件说明
      curFilePath: [], // 文件层级路径
      previewFileData: {}, // 预览文件
      setExtendParams: { // 文件上传参数
        parentId: ''
      }
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    drawerTitle() {
      return '合同模板管理';
    },
    headerCellStyle() {
      return {
        height: '32px',
        padding: 0
      };
    },
    filterList() {
      return [
        { keyword: 'fileName', name: '文件名称', type: 'input', labelWidth: '70px' },
        { keyword: 'creator', name: '创建人', type: 'input', labelWidth: '70px' }
      ];
    },
    fileAccept() {
      return '*';
    },
    showBatchDelBtn() {
      return hasRouteAuth('crm:contract:template:delete');
    }
  },
  watch: {
    dialogVisible(status) {
      status && this.queryEmpty();
    },
    curFolderId(id) {
      this.clearSelect();
      this.setExtendParams.parentId = id;
    }
  },
  methods: {
    queryClick() {
      this.queryFileList();
    },
    queryEmpty() {
      this.curFolderId = '';
      this.fileDesc = '';
      this.paramsObj = {};
      this.curFilePath = [];
      this.clearMixinSelection();
      this.queryFileList();
    },
    queryFileList() {
      const params = _.cloneDeep(this.paramsObj);
      params.id = this.curFolderId;
      params.sortName = this.sortName;
      params.sortType = this.sortType;
      this.listLoading = true;
      queryTemplateList(params).then(res => {
        this.fileList = res.data;
        this.showSearchTips = false;
        if (this.paramsObj.fileName || this.paramsObj.creator) {
          this.curFolderId = '';
          this.fileDesc = '';
          this.curFilePath = [];
          this.showSearchTips = true;
        }
        if (this.setSelectRow) this.setSelectRow(res.data);
        this.listLoading = false;
      }).catch(() => {
        this.listLoading = false;
        this.fileList = [];
      });
    },
    showDelBtn(id) {
      return hasRouteAuth('crm:contract:template:delete') || this.userInfo.id === +id;
    },
    showEditBtn(id) {
      return hasRouteAuth('crm:contract:template:folderEdit') || this.userInfo.id === +id;
    },
    showFolderDialog(edit = false, folderData = null) {
      this.isEdit = edit;
      if (folderData) {
        this.folderData.fileName = folderData.fileName;
        this.folderData.fileDesc = folderData.fileDesc;
        this.folderData.id = folderData.id;
      }
      this.$refs['storeFolderDialog'].dialogVisible = true;
    },
    clearSelect() {
      this.multipleSelectionAll = [];
      this.clearMixinSelection();
    },
    // 文件删除
    onDelete(data) {
      showModal(data.id ? '确认删除此文件吗？' : '确认删除已选中文件吗？').then(() => {
        const ids = [];
        if (data.id) {
          ids.push({ id: data.id, isFolder: data.isFolder, creatorId: data.creatorId });
        } else {
          this.multipleSelectionAll.forEach(rowData => {
            const delRow = Object.create(null);
            delRow.id = rowData.id;
            delRow.isFolder = rowData.isFolder;
            delRow.creatorId = rowData.creatorId;
            ids.push(delRow);
          });
        }
        deleteContractTemplate({ ids }).then(() => {
          data.id && this.resetMultipleSelection(data.id);
          this.$message.success('删除成功');
          !data.id && this.clearMixinSelection();
          this.queryFileList();
        });
      });
    },
    resetMultipleSelection(id) {
      const delIndex = this.multipleSelectionAll.findIndex(item => item.id === id);
      delIndex !== -1 && this.multipleSelectionAll.splice(delIndex, 1);
    },
    // 文件下载
    onDownloadFile(rowData, type) {
      if (type === 1) {
        this.setDownloadParams(rowData, true);
      } else if (type === 2) {
        downloadFile(rowData.filePath, rowData.fileName);
      } else {
        downloadFile(rowData.sourceFilePath, rowData.fileName);
      }
    },
    // 下载/获取填充文件地址
    setDownloadParams(data, isDownload = false) {
      if (this.isFill) {
        const params = Object.create(null);
        params.id = data.id;
        params.contractType = this.contractType;
        params.name = data.fileName;
        this.$emit('downloadTemplate', params, true, isDownload);
      }
      this.previewFileData = data;
    },
    resetFolderData() {
      this.folderData = { fileName: '', fileDesc: '', parentId: null, id: null };
    },
    resetData() {
      this.resetFolderData();
      this.queryFileList();
    },
    // 新建文件夹
    handleFolderCreate() {
      const params = _.cloneDeep(this.folderData);
      params.parentId = this.curFolderId;
      delete params.id;
      this.listLoading = true;
      storeContractTemplate(params).then(() => {
        this.$message.success('创建成功');
        this.listLoading = false;
        this.queryFileList();
      }).catch(() => {
        this.listLoading = false;
      });
    },
    // 编辑文件夹
    handleFolderEdit() {
      const params = _.cloneDeep(this.folderData);
      delete params.parentId;
      this.listLoading = true;
      editContractTemplate(params).then(() => {
        this.$message.success('修改成功');
        this.listLoading = false;
        this.queryFileList();
      }).catch(() => {
        this.listLoading = false;
      });
    },
    onViewFile(rowData) {
      if (!this.isDocx(rowData.fileName) && !rowData.isFolder) return;
      if (rowData.isFolder) {
        this.curFolderId = rowData.id;
        this.curFilePath = this.getPathToArr(rowData.position);
        this.fileDesc = rowData.fileDesc;
        this.paramsObj = {};
        this.queryFileList();
      } else {
        this.previewFileData = rowData;
        this.setDownloadParams(rowData, false);
        this.$refs['ContractPreviewRef'].dialogVisible = true;
      }
    },
    // 当前文件夹路径
    getPathToArr(path, result = []) {
      if (path) {
        result.push({ fileName: path.fileName, id: path.id, fileDesc: path.fileDesc });
        if (path.children) {
          return this.getPathToArr(path.children, result);
        } else {
          return result;
        }
      } else {
        return result;
      }
    },
    // 切换文件夹
    folderChange(index) {
      if (index === 0) {
        this.curFilePath = [];
        this.curFolderId = '';
        this.fileDesc = '';
        this.queryFileList();
      }
      if (index && index < this.curFilePath.length) {
        this.curFilePath.splice(index);
        this.curFolderId = this.curFilePath[index - 1].id;
        this.fileDesc = this.curFilePath[index - 1].fileDesc;
        this.queryFileList();
      }
    },
    // 是否是doc类型
    isDocx(fileName = '') {
      if (!fileName) return false;
      const types = ['docx'];
      const arr = fileName.split('.');
      if (types.includes(arr[arr.length - 1])) {
        return true;
      } else {
        return false;
      }
    },
    sortMethod(a) {
      if (!a.order) {
        this.sortName = '';
        this.sortType = '';
      } else {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      }
      this.queryFileList();
    },
    handleDialogClose() {
      this.dialogVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-drawer__header {
  height: 48px;
  padding: 0 16px;
  margin: 0;
  box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
  > span {
    font-size: 16px;
    color: #333;
    font-weight: bold;
  }
}
::v-deep .el-drawer__body {
  padding: 12px 16px 50px;
  height: calc(100vh - 48px);
  overflow-y: auto;
  @include scrollBar($width:1px);
}
::v-deep .el-table::before {
  height: 0;
}
.linkName{
  cursor: pointer;
  color: #406EFF;
}
.file-table {
  &::v-deep {
    .el-table__row > td {
      border: none;
      height: 32px;
      padding-top: 0;
      padding-bottom: 0;
    }
  }
}
.file-desc {
  background-color: #f9f9f9;
  color: #141C3D;
  font-size: 12px;
  text-align: justify;
  padding: 8px 12px;
  margin-bottom: 12px;
}
.dialog-content {
  position: relative;
  .search-tip {
    color: #999;
    margin-bottom: 12px;
    > span {
      color: #333;
      font-weight: bold;
    }
  }
  .file-icon {
    width: 16px;
    height: 16px;
    vertical-align: middle;
  }
  .action-btn-group {
    display:flex;
    align-items: center;
    > button {
      font-size: 14px;
    }
    .download-btn {
      color: #406EFF;
      margin-left: 10px;
      font-size: 14px;
    }
    .split-line:after {
      content: '|';
      right: -6px;
      top: -1px;
      height: 100%;
      position: relative;
      color: #ddd;
    }
  }
  .file-path {
    margin-bottom: 12px;
    font-size: 14px;
    span {
      white-space: nowrap;
    }
    .active-path {
      color: #406eff;
      cursor: pointer;
    }
    .default-path {
      color: #999;
      cursor: inherit;
    }
  }
  .empty-container {
    margin: 60px auto 0;
    img {
      width: 120px;
      margin: 0 auto;
      display: block;
    }
    .empty-text {
      color: #999;
      font-size: 14px;
      text-align: center;
      margin-top: 16px;
    }
  }
  .mobile-filter-box {
    &::v-deep {
      .mobile-input-component {
        flex-wrap: nowrap;
      }
      .filter-input {
        margin-bottom: 0;
      }
      .changeStatus {
        max-width: 96px;
      }
    }
  }
}
.dialog-footer {
  height: 50px;
  width: 100%;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  background-color: #fff;
  border-top: 1px solid #eee;
  z-index: 5;
  .template-upload-box {
    ::v-deep .circular {
      width: 20px;
      height: 20px;
      margin-top: 11px;
    }
  }
  & ::v-deep{
    .el-upload {
      height: 30px;
    }
    .order-upload {
      padding: 0 !important;
      > div {
        height: 30px;
      }
    }
    .el-upload-dragger {
      width: 100%;
      height: 30px !important;
      background-color: transparent !important;
      border: none;
      border-radius: 2px;
    }
  }
  .btn {
    font-size: 14px;
    padding: 7px 14px;
    margin-right: 16px;
    margin-left: 0;
  }
  .empty-btn-style {
    border-color: #406EFF;
    background: #fff;
    color: #406EFF;
    text-align: center;
    &:hover {
      background: #406EFF;
      color: #fff;
    }
  }
}
.mobile-file-drawer {
  ::v-deep .el-drawer__body {
    padding: 0 0 56px !important;
  }
  .mobile-filter-box {
    padding: 12px 12px 0;
  }
}
</style>
<style lang="scss">
.mobile-file-drawer {
  & td {
    height: 40px !important;
  }
}
</style>
